﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using BAL.EstRec;
using Nav3.EventArgs;


namespace Nav3
{
    /// <summary>
    /// Lógica de interacción para NavControl.xaml
    /// </summary>
    public partial class NavControl : UserControl
    {
        private int cont;
        public TextBox txtBoxCurrent;
        private bool canAddControl;
        private TagCreateControl currentItem;
        private TagCreateControl Aux;
        private TagCreateControl selectedItem;// cambio de private a public
        private bool IsFDVMode;
        private string positionCode;

        public NavControl()
        {
            this.cont = 0;
            this.txtBoxCurrent = null;
            InitializeComponent();

            //Indica si puede agergar otro control cuando se presiona el boton de nuevo.
            //Esto para evitar que se agreguen dos controles si no se ha guardado el primero.
            try
            {
                this.canAddControl = true;
                //this.loadData();
                this.currentItem = null;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error al cargar de la base de datos : Ex : " + ex.Message + "; inner : " + ex.InnerException, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        public void init(bool isFDVMode, string positionCode)
        {
            this.positionCode = positionCode;
            this.IsFDVMode = isFDVMode;
            //this.loadData();
        }

        public void loadData()
        {
            if (this.IsFDVMode)
            {
                this.loadFdvData();
                this.setFdvMode();
            }
            else
            {
                this.loadDataAll();
                this.setHqMode();
            }

            //Cargar la versión actual
            if (this.selectedItem != null)
            {
                this.selectItemByUnidVersion(this.selectedItem.idElement);
            }
            else
            {
                this.selectItemByUnidVersion(0);
            }

        }

        private void btnNuevo_Click(object sender, RoutedEventArgs e)
        {
            if (this.canAddControl)
            {
                this.canAddControl = false;

                TagCreateControl tcc = this.createTagControl(null);
                this.spItemCont.Children.Add(tcc);
                tcc.changeToEditing();
            }
        }

        public void loadDataAll()
        {
            List<BgtVersion> versiones;

            try
            {
                //int count = 0;
                versiones = BgtVersion.GetVersion();
                this.removeTagControls();

                foreach (BgtVersion v in versiones)
                {
                    TagCreateControl tcc = this.createTagControl(v);
                    this.spItemCont.Children.Add(tcc);

                    //if (count == 0)
                    //{
                    //    if (this.selectedItem != null)
                    //    {
                    //        this.selectedItem.setNoSelected();
                    //        this.selectedItem = (TagCreateControl)tcc;
                    //        this.selectedItem.setSelected();
                    //    }
                    //    else
                    //    {
                    //        this.selectedItem = (TagCreateControl)tcc;
                    //        this.selectedItem.setSelected();
                    //    }

                    //    this.RaiseSelectItemEvent(((TagCreateControl)(tcc)).lblName);
                    //    this.currentItem = null;
                    //    this.Aux = tcc;
                    //}

                    //count++;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public void loadFdvData()
        {
            List<FdvVersion> versiones;

            try
            {
                int count = 0;
                //versiones = FdvVersion.f
                versiones = FdvVersion.GetListFdvVersionByTerritorio(positionCode);
                this.removeTagControls();

                foreach (FdvVersion v in versiones)
                {
                    TagCreateControl tcc = this.createTagControlByFdv(v);
                    this.spItemCont.Children.Add(tcc);

                    //if (count == 0)
                    //{
                    //    if (this.selectedItem != null)
                    //    {
                    //        this.selectedItem.setNoSelected();
                    //        this.selectedItem = (TagCreateControl)tcc;
                    //        this.selectedItem.setSelected();
                    //    }
                    //    else
                    //    {
                    //        this.selectedItem = (TagCreateControl)tcc;
                    //        this.selectedItem.setSelected();
                    //    }

                    //    this.RaiseSelectItemEvent(((TagCreateControl)(tcc)).lblName);
                    //    this.currentItem = null;
                    //    this.Aux = tcc;
                    //}

                    //count++;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private void removeTagControls()
        {
            List<Control> controls = new List<Control>();
            foreach (Control c in this.spItemCont.Children)
            {
                controls.Add(c);
            }
            foreach (Control c in controls)
            {
                this.spItemCont.Children.Remove(c);
            }
        }

        private TagCreateControl createTagControl(BgtVersion version)//cambio de private a public
        {
            if (version == null)
                version = new BgtVersion();

            TagCreateControl tcc = new TagCreateControl();
            tcc.setControlData(version.unid, version.name, version.isPublished, version.isSend);

            tcc.SaveItem += delegate(object tccSender, RoutedEventArgs tccArgs)
            {
                this.canAddControl = true;
            };
            tcc.OnEditing += delegate(object tccOnEditingSender, RoutedEventArgs tccOnEditingEventArgs)
            {
                this.canAddControl = false;
                this.currentItem = tcc;
            };
            tcc.ClickEdit += delegate(object tccClickEditSender, RoutedEventArgs tccClickEditEventArgs)
            {
                if (this.currentItem != null)
                {
                    this.currentItem.changeToRead();
                }
            };
            //tcc.Click += new RoutedEventHandler(selectItem);
            tcc.Click += new RoutedEventHandler(TagControl_Click);
            tcc.PostEscape += new RoutedEventHandler(postEscapeItem);

            return tcc;
        }

        /// <summary>
        /// Controla el click del tag control interno. Bajo este, se programa la lógica que
        /// dispara el evento de selectitem de Nav
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="re"></param>
        private void TagControl_Click(object sender, RoutedEventArgs re)
        {
            //Cuando se la click al control que tiene el nombre de la versión, se tiene que validar
            //si es diferente al unid del que actualmente está seleccionado
            if (this.selectedItem != null)
            {
                if (this.selectedItem.idElement != (sender as TagCreateControl).idElement)
                {
                    this.selectedItem.setNoSelected();
                    this.selectedItem = (sender as TagCreateControl);
                    this.selectedItem.setSelected();
                    this.RaiseSelectItemEvent(((TagCreateControl)(sender)).lblName);
                }
            }
            else
            {
                this.selectedItem = (sender as TagCreateControl);
                this.selectedItem.setSelected();
                this.RaiseSelectItemEvent(((TagCreateControl)(sender)).lblName);
            }
        }

        private TagCreateControl createTagControlByFdv(FdvVersion version)//cambio de private a public
        {
            if (version == null)
                version = new FdvVersion();

            TagCreateControl tcc = new TagCreateControl();
            tcc.setControlData(version.UnidFdvBgtVersion, version.Name, (version.DatePublished != DateTime.MinValue) ? true : false, false);

            tcc.SaveItem += delegate(object tccSender, RoutedEventArgs tccArgs)
            {
                this.canAddControl = true;
            };
            tcc.OnEditing += delegate(object tccOnEditingSender, RoutedEventArgs tccOnEditingEventArgs)
            {
                this.canAddControl = false;
                this.currentItem = tcc;
            };
            tcc.ClickEdit += delegate(object tccClickEditSender, RoutedEventArgs tccClickEditEventArgs)
            {
                if (this.currentItem != null)
                {
                    this.currentItem.changeToRead();
                }
            };
            tcc.Click += new RoutedEventHandler(TagControl_Click);
            tcc.PostEscape += new RoutedEventHandler(postEscapeItem);

            return tcc;
        }

        private void Label_MouseUp(object sender, MouseButtonEventArgs e)
        {

        }

        private void selectItem(object tccSender, RoutedEventArgs tccEventArgs)
        {
            if (this.selectedItem != null)
            {
                this.selectedItem.setNoSelected();
                this.selectedItem = (TagCreateControl)tccSender;
                this.selectedItem.setSelected();
            }
            else
            {
                this.selectedItem = (TagCreateControl)tccSender;
                this.selectedItem.setSelected();
            }

            this.RaiseSelectItemEvent(((TagCreateControl)(tccSender)).lblName);
        }

        /// <summary>
        /// Busca dentro de los tag create controls el unidVersion
        /// Si lo encuentra, dispara la selección del elemento
        /// Si no lo encuentra, dispara la selección del primer item
        /// </summary>
        /// <param name="unidVersion"></param>
        private void selectItemByUnidVersion(long unidVersion)
        {
            bool unidVersionExists = false;
            foreach (Control c in this.spItemCont.Children)
            {
                if (c.GetType() == typeof(TagCreateControl))
                {
                    if ((c as TagCreateControl).idElement == unidVersion)
                    {
                        this.selectItem(c as TagCreateControl, new RoutedEventArgs());
                        unidVersionExists = true;
                        break;
                    }
                }
            }

            if (!unidVersionExists)
            {
                try
                {
                    this.selectItem(((TagCreateControl)this.spItemCont.Children[0]), new RoutedEventArgs());
                }
                catch (Exception ex)
                {
                    ;
                }
            }
        }

        public void postEscapeItem(object tccSender, RoutedEventArgs tccEventArgs)
        {
            this.canAddControl = true;
        }

        private void setFdvMode()
        {
            this.hiddeNewBotton();
            this.hideTagEdit();
            this.IsFDVMode = true;
        }

        private void setHqMode()
        {
            this.showNewBotton();
            this.showTagEdit();
            this.IsFDVMode = false;
        }

        private void hiddeNewBotton()
        {
            this.spNewBoton.Visibility = Visibility.Collapsed;
        }

        private void showNewBotton()
        {
            this.spNewBoton.Visibility = Visibility.Visible;
        }

        private void hideTagEdit()
        {
            foreach (var c in this.spItemCont.Children)
            {
                ((Label)((TagCreateControl)c).FindName("lblCerrar")).Visibility = Visibility.Hidden;
                ((Label)((TagCreateControl)c).FindName("lblEditar")).Visibility = Visibility.Hidden;
            }
        }

        private void showTagEdit()
        {
            foreach (var c in this.spItemCont.Children)
            {
                ((Label)((TagCreateControl)c).FindName("lblCerrar")).Visibility = Visibility.Visible;
                ((Label)((TagCreateControl)c).FindName("lblEditar")).Visibility = Visibility.Hidden;
            }
        }

        public TagCreateControl getSelectedItem()
        {
            return this.selectedItem;
        }

        //Eventos
        #region events definition
        public static readonly RoutedEvent NewItemEvent = EventManager.RegisterRoutedEvent(
            "NewItem", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(NavControl));

        public event RoutedEventHandler NewItem
        {
            add { AddHandler(NewItemEvent, value); }
            remove { RemoveHandler(NewItemEvent, value); }
        }
        void RaiseNewItemEvent()
        {
            RoutedEventArgs newEventArgs = new RoutedEventArgs(NavControl.NewItemEvent);
            RaiseEvent(newEventArgs);
        }

        public static readonly RoutedEvent SelectItemEvent = EventManager.RegisterRoutedEvent(
            "SelectItem", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(NavControl));
        public event RoutedEventHandler SelectItem
        {
            add { AddHandler(SelectItemEvent, value); }
            remove { RemoveHandler(SelectItemEvent, value); }
        }
        void RaiseSelectItemEvent(object sender)
        {
            //MessageBox.Show(((Label)sender).Content.ToString());
            SelectItemEventArgs newEventArgs = new SelectItemEventArgs(NavControl.SelectItemEvent);
            newEventArgs.name = ((Label)sender).Content.ToString();
            newEventArgs.unid = this.selectedItem.idElement;
            RaiseEvent(newEventArgs);
        }
        #endregion events definition
    }
}
